package com.sjm.suchbear.easymap;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.sjm.suchbear.easymap.Model.FinishModel;
import com.sjm.suchbear.easymap.Model.RiverGoModel;
import com.sjm.suchbear.easymap.Model.TraceModel;
import com.sjm.suchbear.easymap.Service.UpLocService;
import com.sjm.suchbear.easymap.Service.iHttpService;
import com.sjm.suchbear.easymap.Util.DialogLoading;
import com.sjm.suchbear.easymap.Util.HttpUtils;
import com.sjm.suchbear.easymap.Util.PermissionHelper;
import com.sjm.suchbear.easymap.Util.SP;
import com.sjm.suchbear.easymap.Util.T;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;
import zilla.libcore.util.Util;

import static java.lang.Math.atan2;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.bmapView)
    MapView bmapView;
    @BindView(R.id.et_searchKeyWord)
    EditText etSearchKeyWord;
    @BindView(R.id.iv_searchTid)
    ImageView ivSearchTid;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.ll_search)
    LinearLayout llSearch;
    @BindView(R.id.tv_searchResultName)
    TextView tvSearchResultName;
    @BindView(R.id.tv_searchResultAddress)
    TextView tvSearchResultAddress;
    @BindView(R.id.ll_searchResult)
    LinearLayout llSearchResult;
    @BindView(R.id.iv_river)
    ImageView ivRiver;
    @BindView(R.id.tv_goTask)
    TextView tvGoTask;
    @BindView(R.id.tv_goHistory)
    TextView tvGoHistory;
    @BindView(R.id.rl_mode1)
    RelativeLayout rlMode1;
    @BindView(R.id.ll_button)
    LinearLayout llButton;
    @BindView(R.id.ll_Reportbutton)
    LinearLayout llReportbutton;

    private BaiduMap mBaiduMap;
    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    private List<String> needPermission;
    private final int REQUEST_CODE_PERMISSION = 0;
    private String[] permissionArray = new String[]{
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    private static double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    private String mcity;
    private LatLng mLatlng;
    private static int SearchCode = 0x001;
    private static int NEWRESULT = 0x011;
    private static int POSTCOMMENT = 0x111;
    private int isnew = 0;
    private int showMode; //0:普通搜索模式 1:搜索结果模式 2.巡河中模式 3.普通登录模式 4.任务巡河中模式 5.绘制结果
    private String taskID = "";
    private String patrolId;

    private String searchName;
    private String searchLocation;
    private iHttpService service;
    private TraceModel mTracemodel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //在使用SDK各组件之前初始化context信息，传入ApplicationContext
        //注意该方法要再setContentView方法之前实现
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        //AddressManager.getInstance(getApplicationContext());
        service = HttpUtils.createService(this);
        showMode = getIntent().getIntExtra("model", 0);
        if (showMode == 0 || showMode == 1 || showMode == 2 || showMode == 3) {
            initView();
        }
        if (showMode == 4) {
            taskID = getIntent().getStringExtra("taskID");
            startTaskRiver();
        } else if (showMode == 5) {
            initView();
            patrolId = getIntent().getStringExtra("patrolId");
            getPatrolInfo();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onNewIntent(Intent intent) {
        showMode = intent.getIntExtra("model", 0);
        if (showMode == 4) {
            taskID = intent.getStringExtra("taskID");
            startTaskRiver();
        } else if (showMode == 5) {
            initView();
            patrolId = intent.getStringExtra("patrolId");
            getPatrolInfo();
        }

    }

    private void initView() {
        switch (showMode) {
            case 0:
                //只显示搜索
                rlMode1.setVisibility(View.VISIBLE);
                llSearchResult.setVisibility(View.GONE);
                ivRiver.setVisibility(View.GONE);
                llButton.setVisibility(View.GONE);
                llReportbutton.setVisibility(View.GONE);
                llSearch.setVisibility(View.VISIBLE);
                //初始化定位
                mLocationClient = new LocationClient(getApplicationContext());
                //声明LocationClient类
                mLocationClient.registerLocationListener(myListener);
                //注册监听函数
                initLocation();
                askMultiplePermission();
                break;
            case 1:
                rlMode1.setVisibility(View.GONE);
                llSearchResult.setVisibility(View.VISIBLE);
                llSearch.setVisibility(View.GONE);
                tvSearchResultName.setText(searchName);
                tvSearchResultAddress.setText(searchLocation);
                addPoint(bd_encrypt(searchLocation));
                centerToLocation(bd_encrypt(searchLocation));
                break;
            case 3:
                //不显示搜索
                rlMode1.setVisibility(View.VISIBLE);
                llSearchResult.setVisibility(View.GONE);
                llSearch.setVisibility(View.GONE);
                llButton.setVisibility(View.VISIBLE);
                llReportbutton.setVisibility(View.GONE);
                ivRiver.setVisibility(View.VISIBLE);
                ivRiver.setImageResource(R.drawable.river_begin);

                //初始化定位
                mLocationClient = new LocationClient(getApplicationContext());
                //声明LocationClient类
                mLocationClient.registerLocationListener(myListener);
                //注册监听函数
                initLocation();
                askMultiplePermission();
                break;

            case 2:
                rlMode1.setVisibility(View.VISIBLE);
                llSearchResult.setVisibility(View.GONE);
                llSearch.setVisibility(View.GONE);
                llButton.setVisibility(View.GONE);
                llReportbutton.setVisibility(View.GONE);
                ivRiver.setVisibility(View.VISIBLE);
                ivRiver.setImageResource(R.drawable.river_end);

                //初始化定位
                mLocationClient = new LocationClient(getApplicationContext());
                //声明LocationClient类
                mLocationClient.registerLocationListener(myListener);
                //注册监听函数
                //initLocation();
                askMultiplePermission();
                break;

            case 4:
                rlMode1.setVisibility(View.VISIBLE);
                llSearchResult.setVisibility(View.GONE);
                llSearch.setVisibility(View.GONE);
                llButton.setVisibility(View.GONE);
                llReportbutton.setVisibility(View.GONE);
                ivRiver.setVisibility(View.VISIBLE);
                ivRiver.setImageResource(R.drawable.river_end);

                //初始化定位
                mLocationClient = new LocationClient(getApplicationContext());
                //声明LocationClient类
                mLocationClient.registerLocationListener(myListener);
                //注册监听函数
                //initLocation();
                askMultiplePermission();
                break;

            case 5:
                rlMode1.setVisibility(View.VISIBLE);
                llSearchResult.setVisibility(View.GONE);
                llSearch.setVisibility(View.GONE);
                llButton.setVisibility(View.GONE);
                ivRiver.setVisibility(View.GONE);
                llReportbutton.setVisibility(View.VISIBLE);

                break;
        }
    }

    public void askMultiplePermission() {
        needPermission = new ArrayList<>();
        for (String permissionName :
                permissionArray) {
            if (!PermissionHelper.checkIsAskPermission(this, permissionName)) {
                needPermission.add(permissionName);
            }
        }

        if (needPermission.size() > 0) {
            //开始申请权限
            ActivityCompat.requestPermissions(this, needPermission.toArray(new String[needPermission.size()]), REQUEST_CODE_PERMISSION);
        } else {
            //获取数据
            mLocationClient.start();
            RefreshLocation refreshLocation = new RefreshLocation();
            refreshLocation.start();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CODE_PERMISSION:
                Map<String, Integer> permissionMap = new HashMap<>();
                for (String name :
                        needPermission) {
                    permissionMap.put(name, PackageManager.PERMISSION_GRANTED);
                }

                for (int i = 0; i < permissions.length; i++) {
                    permissionMap.put(permissions[i], grantResults[i]);
                }
                if (PermissionHelper.checkIsAskPermissionState(permissionMap, permissions)) {
                    //获取数据
                    mLocationClient.start();
                    RefreshLocation refreshLocation = new RefreshLocation();
                    refreshLocation.start();
                } else {
                    //提示权限获取不完成，可能有的功能不能使用
                    T.showShort(getBaseContext(), "没有成功获取权限，部分功能受限");
                }

                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            //showmode为1则返回0
            if (showMode == 1) {
                mBaiduMap.clear();
                showMode = 0;
                initView();
                return true;
            }
            return super.onKeyDown(keyCode, event);
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }

    @OnClick({R.id.tv_search, R.id.tv_goTask, R.id.tv_goHistory, R.id.iv_river, R.id.ll_Reportbutton})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.tv_search:
                if (mcity != null) {
                    if (!mcity.equals("")) {
                        intent = new Intent(this, SearchActivity.class);
                        intent.putExtra("mcity", mcity);
                        intent.putExtra("mLatlng", mLatlng);
                        startActivityForResult(intent, SearchCode);
                    } else {
                        T.showShort(getBaseContext(), "未定位成功，无法搜索");
                    }
                } else {
                    mLocationClient.requestLocation();//重新定位
                }
                break;
            case R.id.tv_goTask:
                intent = new Intent(this, TaskListActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_goHistory:
                intent = new Intent(this, HistoryActivity.class);
                startActivity(intent);
                break;
            case R.id.iv_river:
                if (showMode == 3) {
                    startNolmalRiver();
                } else {
                    //结束service 结束巡河
                    finishPatrol();
                }
                break;
            case R.id.ll_Reportbutton:
                //打开巡查结果内容
                if (mTracemodel.getContent() != null || !mTracemodel.getImglist().get(0).getImgurl().equals("") || !mTracemodel.getVediourl().equals("") || isnew == 1) {
                    //Log.i("MainActivity",mTracemodel.getImglist().get(0).getImgurl());
                    //Log.i("MainActivity",mTracemodel.getVediourl());
                    //上传过巡查内容
                    intent = new Intent(this, HistoryDetilActivity.class);
                    intent.putExtra("showmode", 1);
                    intent.putExtra("patrolId", mTracemodel.getPatrolId());
                    startActivity(intent);
                } else {
                    //没有上传过
                    intent = new Intent(this, HistoryDetilActivity.class);
                    intent.putExtra("showmode", 0);
                    intent.putExtra("patrolId", mTracemodel.getPatrolId());
                    startActivityForResult(intent, POSTCOMMENT);
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == SearchCode) {
            searchLocation = data.getStringExtra("location");
            searchName = data.getStringExtra("name");
            showMode = 1;
            initView();
        }
        if (requestCode == POSTCOMMENT && resultCode == NEWRESULT) {
            isnew = 1;
        }
    }


    protected void initMap(BDLocation location) {
        mBaiduMap = bmapView.getMap();
        mBaiduMap.setMyLocationEnabled(true);
        mcity = location.getCity();
        mLatlng = new LatLng(location.getLatitude(), location.getLongitude());
        //MyLocationConfiguration.LocationMode mCurrentMode = MyLocationConfiguration.LocationMode.FOLLOWING;//定位跟随态
        MyLocationConfiguration.LocationMode mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;   //默认为 LocationMode.NORMAL 普通态
        //mCurrentMode = LocationMode.COMPASS;  //定位罗盘态

        // 构造定位数据
        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(location.getRadius())
                // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(0).latitude(location.getLatitude())
                .longitude(location.getLongitude()).build();

        // 设置定位数据
        mBaiduMap.setMyLocationData(locData);
        // 设置定位图层的配置（定位模式，是否允许方向信息，用户自定义定位图标）
        /*BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
                .fromResource(R.drawable.icon_geo);
        MyLocationConfiguration config = new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker);
        mBaiduMap.setMyLocationConfiguration(config);*/
        centerToLocation(location);
        //addPoint(location);
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                //mBaiduMap.clear();
                //addPoint(latLng);
                //centerToLocation(latLng, 180);
                //etSearchKeyWord.clearFocus();
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });
        //mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration());
    }

    protected void centerToLocation(LatLng latLng) {
        //LatLng cenpt = new LatLng(latLng.latitude, latLng.longitude);
        //定义地图状态,地图缩放级别 3~19
        MapStatus newMapStatus = new MapStatus.Builder().target(latLng).zoom(15).build();
        //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(newMapStatus);
        //改变地图状态
        //mBaiduMap.animateMapStatus(mMapStatusUpdate, duration);
        mBaiduMap = bmapView.getMap();
        mBaiduMap.setMyLocationEnabled(true);
        mBaiduMap.setMapStatus(mMapStatusUpdate);
    }

    protected void centerToLocation(BDLocation location) {
        LatLng cenpt = new LatLng(location.getLatitude(), location.getLongitude());
        //定义地图状态,地图缩放级别 3~19
        MapStatus newMapStatus = new MapStatus.Builder().target(cenpt).zoom(19).build();
        //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(newMapStatus);
        //改变地图状态
        //mBaiduMap.animateMapStatus(mMapStatusUpdate, duration);
        mBaiduMap = bmapView.getMap();
        mBaiduMap.setMyLocationEnabled(true);
        mBaiduMap.setMapStatus(mMapStatusUpdate);
    }

    protected void addPoint(BDLocation location) {
        //定义Maker坐标点

        LatLng point = new LatLng(location.getLatitude(), location.getLongitude());

        //构建Marker图标

        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.img_red);

        //构建MarkerOption，用于在地图上添加Marker

        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap);

        //在地图上添加Marker，并显示

        mBaiduMap.addOverlay(option);
    }

    protected void addPoint(LatLng latLng) {
        //定义Maker坐标点

        LatLng point = new LatLng(latLng.latitude, latLng.longitude);

        //构建Marker图标

        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.img_red_1);

        //构建MarkerOption，用于在地图上添加Marker

        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap);

        //在地图上添加Marker，并显示

        mBaiduMap.addOverlay(option);
    }

    //开始普通巡河
    private void startNolmalRiver() {
        service.getPatrolIdbynomal(SP.getUid(getBaseContext()))
                .subscribeOn(Schedulers.io())//指定网络请求在IO线程
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        DialogLoading.StartLodingDialog(MainActivity.this);
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())//显示Dialog在主线程中
                .observeOn(AndroidSchedulers.mainThread())//显示数据在主线程
                .subscribe(new Subscriber<RiverGoModel>() {
                    @Override
                    public void onCompleted() {
                        DialogLoading.StopLodingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        DialogLoading.StopLodingDialog();
                        Util.toastMsg("网络连接失败");
                    }

                    @Override
                    public void onNext(RiverGoModel riverGoModel) {
                        if (!riverGoModel.getPatrolId().equals("")) {
                            Util.toastMsg("开始巡河");
                            patrolId = riverGoModel.getPatrolId();
                            showMode = 2;
                            initView();
                            initLocation2();
                            Intent normalRiver = new Intent(MainActivity.this, UpLocService.class);
                            normalRiver.putExtra("patrolId", patrolId);
                            startService(normalRiver);
                        } else {
                            Util.toastMsg(riverGoModel.getMsg());
                        }
                    }
                });
    }

    //开始任务巡河
    private void startTaskRiver() {
        service.getPatrolIdbytask(SP.getUid(getBaseContext()), taskID)
                .subscribeOn(Schedulers.io())//指定网络请求在IO线程
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        DialogLoading.StartLodingDialog(MainActivity.this);
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())//显示Dialog在主线程中
                .observeOn(AndroidSchedulers.mainThread())//显示数据在主线程
                .subscribe(new Subscriber<RiverGoModel>() {
                    @Override
                    public void onCompleted() {
                        DialogLoading.StopLodingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        DialogLoading.StopLodingDialog();
                        Util.toastMsg("网络连接失败");
                    }

                    @Override
                    public void onNext(RiverGoModel riverGoModel) {
                        if (!riverGoModel.getPatrolId().equals("")) {
                            Util.toastMsg("开始巡河");
                            patrolId = riverGoModel.getPatrolId();
                            showMode = 4;
                            initView();
                            initLocation2();
                            Intent taskRiver = new Intent(MainActivity.this, UpLocService.class);
                            taskRiver.putExtra("patrolId", patrolId);
                            startService(taskRiver);
                        } else {
                            Util.toastMsg(riverGoModel.getMsg());
                        }
                    }
                });
    }

    //结束巡河
    private void finishPatrol() {
        service.finishPatrol(patrolId)
                .subscribeOn(Schedulers.io())//指定网络请求在IO线程
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        DialogLoading.StartLodingDialog(MainActivity.this);
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())//显示Dialog在主线程中
                .observeOn(AndroidSchedulers.mainThread())//显示数据在主线程
                .subscribe(new Subscriber<FinishModel>() {
                    @Override
                    public void onCompleted() {
                        DialogLoading.StopLodingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        DialogLoading.StopLodingDialog();
                        Util.toastMsg("网络连接失败");
                    }

                    @Override
                    public void onNext(FinishModel finishModel) {
                        mLocationClient.stop();
                        if (finishModel.getFinishPatrol().equals("1")) {
                            Util.toastMsg("巡河结束");
                            showMode = 3;
                            initView();
                            stopService(new Intent(MainActivity.this, UpLocService.class));
                        } else {
                            Util.toastMsg("巡河结束失败");
                            showMode = 3;
                            initView();
                            stopService(new Intent(MainActivity.this, UpLocService.class));
                        }
                    }
                });
    }

    private void getPatrolInfo() {
        service.getPatrolInfo(patrolId)
                .subscribeOn(Schedulers.io())//指定网络请求在IO线程
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        DialogLoading.StartLodingDialog(MainActivity.this);
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())//显示Dialog在主线程中
                .observeOn(AndroidSchedulers.mainThread())//显示数据在主线程
                .subscribe(new Subscriber<TraceModel>() {
                    @Override
                    public void onCompleted() {
                        DialogLoading.StopLodingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        DialogLoading.StopLodingDialog();
                        Util.toastMsg("网络连接失败");
                    }

                    @Override
                    public void onNext(TraceModel traceModel) {
                        mTracemodel = traceModel;
                        //定位到初始点
                        if (traceModel.getTrace().size() > 1) {
                            LatLng latLng = new LatLng(Double.parseDouble(traceModel.getTrace().get(0).getLat()), Double.parseDouble(traceModel.getTrace().get(0).getLng()));
                            centerToLocation(latLng);
                            List<LatLng> points = new ArrayList<LatLng>();
                            for (int i = 0; i < traceModel.getTrace().size(); i++) {
                                LatLng mlatlng = new LatLng(Double.parseDouble(traceModel.getTrace().get(i).getLat()), Double.parseDouble(traceModel.getTrace().get(i).getLng()));
                                points.add(mlatlng);
                            }
                            drawMap(points);
                        } else {
                            if (traceModel.getTrace().size() == 1) {
                                LatLng latLng = new LatLng(Double.parseDouble(traceModel.getTrace().get(0).getLat()), Double.parseDouble(traceModel.getTrace().get(0).getLng()));
                                centerToLocation(latLng);
                            } else {
                                Util.toastMsg("暂无地图数据");
                            }
                        }
                    }
                });
    }

    //初次定位
    private class RefreshLocation extends Thread {
        int error = 1;

        @Override
        public void run() {
            super.run();
            for (int i = 0; i < 3; i++) { //进行10S后台定位，未获取则提示定位失败
                int location = mLocationClient.requestLocation();
                if (location == 0) {
                    error = 0;
                    break;
                } else {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            if (error == 1) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        T.showShort(getBaseContext(), "定位失败");
                    }
                });
            }
        }
    }

    private void initLocation() {

        LocationClientOption option = new LocationClientOption();

        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，设置定位模式，默认高精度
        //LocationMode.Hight_Accuracy：高精度；
        //LocationMode. Battery_Saving：低功耗；
        //LocationMode. Device_Sensors：仅使用设备；

        option.setCoorType("bd09ll");
        //可选，设置返回经纬度坐标类型，默认gcj02
        //gcj02：国测局坐标；
        //bd09ll：百度经纬度坐标；
        //bd09：百度墨卡托坐标；
        //海外地区定位，无需设置坐标类型，统一返回wgs84类型坐标

        option.setScanSpan(0);
        //可选，设置发起定位请求的间隔，int类型，单位ms
        //如果设置为0，则代表单次定位，即仅定位一次，默认为0
        //如果设置非0，需设置1000ms以上才有效

        option.setOpenGps(true);
        //可选，设置是否使用gps，默认false
        //使用高精度和仅用设备两种定位模式的，参数必须设置为true

        option.setLocationNotify(true);
        //可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false

        option.setIgnoreKillProcess(false);
        //可选，定位SDK内部是一个service，并放到了独立进程。
        //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)

        option.SetIgnoreCacheException(false);
        //可选，设置是否收集Crash信息，默认收集，即参数为false

        option.setWifiCacheTimeOut(5 * 60 * 1000);
        //可选，7.2版本新增能力
        //如果设置了该接口，首次启动定位时，会先判断当前WiFi是否超出有效期，若超出有效期，会先重新扫描WiFi，然后定位

        option.setEnableSimulateGps(false);
        //可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false

        option.setIsNeedAddress(true);

        mLocationClient.setLocOption(option);
        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明
    }

    private void initLocation2() {

        LocationClientOption option = new LocationClientOption();

        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，设置定位模式，默认高精度
        //LocationMode.Hight_Accuracy：高精度；
        //LocationMode. Battery_Saving：低功耗；
        //LocationMode. Device_Sensors：仅使用设备；

        option.setCoorType("bd09ll");
        //可选，设置返回经纬度坐标类型，默认gcj02
        //gcj02：国测局坐标；
        //bd09ll：百度经纬度坐标；
        //bd09：百度墨卡托坐标；
        //海外地区定位，无需设置坐标类型，统一返回wgs84类型坐标

        option.setScanSpan(5000);
        //可选，设置发起定位请求的间隔，int类型，单位ms
        //如果设置为0，则代表单次定位，即仅定位一次，默认为0
        //如果设置非0，需设置1000ms以上才有效

        option.setOpenGps(true);
        //可选，设置是否使用gps，默认false
        //使用高精度和仅用设备两种定位模式的，参数必须设置为true

        option.setLocationNotify(true);
        //可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false

        option.setIgnoreKillProcess(false);
        //可选，定位SDK内部是一个service，并放到了独立进程。
        //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)

        option.SetIgnoreCacheException(false);
        //可选，设置是否收集Crash信息，默认收集，即参数为false

        option.setWifiCacheTimeOut(5 * 60 * 1000);
        //可选，7.2版本新增能力
        //如果设置了该接口，首次启动定位时，会先判断当前WiFi是否超出有效期，若超出有效期，会先重新扫描WiFi，然后定位

        option.setEnableSimulateGps(false);
        //可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false

        option.setIsNeedAddress(true);

        mLocationClient.setLocOption(option);
        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        //报错更换为extends
        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取经纬度相关（常用）的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
            initMap(location);

            //double latitude = location.getLatitude();    //获取纬度信息
            //double longitude = location.getLongitude();    //获取经度信息
            //float radius = location.getRadius();    //获取定位精度，默认值为0.0f

            //String coorType = location.getCoorType();
            //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准

            //int errorCode = location.getLocType();
            //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
        }

        @Override
        public void onLocDiagnosticMessage(int i, int i1, String s) {
            super.onLocDiagnosticMessage(i, i1, s);
            Log.i("easymap", s);
        }
    }

    private void drawMap(List<LatLng> points) {
        //绘制折线
        OverlayOptions ooPolyline = new PolylineOptions().width(10)
                .color(0xAAFF0000).points(points);
        Polyline mPolyline = (Polyline) mBaiduMap.addOverlay(ooPolyline);
    }

    /**
     * 将火星坐标转变成百度坐标
     *
     * @param lngLat_gd 火星坐标（高德、腾讯地图坐标等）
     * @return 百度坐标
     */

    public static LatLng bd_encrypt(String lngLat_gd) {
        String[] locationarray = lngLat_gd.split(",");

        double x = Double.parseDouble(locationarray[1]),
                y = Double.parseDouble(locationarray[0]);
        double z = sqrt(x * x + y * y) + 0.00002 * sin(y * x_pi);
        double theta = atan2(y, x) + 0.000003 * cos(x * x_pi);
        return new LatLng(dataDigit(6, z * cos(theta) + 0.0065), dataDigit(6, z * sin(theta) + 0.006));

    }

    /**
     * 对double类型数据保留小数点后多少位
     * 高德地图转码返回的就是 小数点后6位，为了统一封装一下
     *
     * @param digit 位数
     * @param in    输入
     * @return 保留小数位后的数
     */
    static double dataDigit(int digit, double in) {
        return new BigDecimal(in).setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();

    }


}
